#coding = utf-8
from deal_db import get_deal_from_db as get_deal

class DealAnalyzer:

    def __init__(self, con, code, exdate):

        self.con = con
        self.code = code
        self.exdate = exdate
        
        self.data = self.get_deal_data()

    def get_deal_data(self):
        
        data = get_deal(self.con, self.code, self.exdate)
        
        def p(i):
            
            m = i[3] * i[4]
            i = i[2:]
            i.append(m)
            
            return i

        data = [p(i) for i in data]

        return data

    def set_thresholds(self, gt=[1000000 ,500000], lt=[100000 ,50000]):

        self.gt = gt
        self.lt = lt

    def analyse_by_threshold(self):

        def c(data):
            r = [len(data), ]
            
            b = [i for i in data if i[-2]=='b']            
            r.append(len(b))

            s = [i for i in data if i[-2]=='s']            
            r.append(len(s))
            
            
            r.append(sum(b) - sum(s))

            return r
        
        r = []  
        
        for t in self.gt:
            h = [">", t]
            data = [i for i in self.data if i[-1] > t]
            r.append(h + c(data))
        
        for t in self.lt:
            h = ['<', t]
            data = [i for i in self.data if i[-1] < t]
            r.append(h + c(data))

        #no threshold
        h = ['a', 'a']
        r.append(h + c(self.data))

        self.r_by_threshold = r

    def get_results_by_threshold(self):
        
        self.analyse_by_threshold()
        return self.r_by_threshold

            
    
